
local StringUtil = require("util.StringUtil")
print("balancer by lua");
local balancer = require "ngx.balancer"

--这里写死ip 地址和端口 后期可以通过服务发现的方式去查找 比如通过consul
local host = {"127.0.0.1:8088", "127.0.0.1:8087"}

local backend = ""

local port = ngx.var.server_port

local remote_ip = ngx.var.remote_addr

local key = remote_ip..port

local hash = ngx.crc32_long(key);

hash = (hash % 2) + 1

ngx.log(ngx.ERR, "hash=", hash)

backend = host[hash]

print("balance to ip :".. backend);

ngx.log(ngx.ERR, "backend=", backend)

local ip_port = StringUtil.split(backend,":");

local ok, err = balancer.set_current_peer(ip_port[1], ip_port[2]);

if not ok then
    ngx.log(ngx.ERR, "failed to set the current peer: ", err)
    return ngx.exit(500)
end

ngx.log(ngx.DEBUG, "current peer ", backend)